<template>
  	<el-main v-loading="showLoading">
		<div class="margin_bottom_30">
			<el-button type="primary" size="small"  @click="openAdd()">新增账号</el-button>
		</div>

		<el-table
			:data="dataList"
			border
			height="700"
			style="width: 100%"
			:header-cell-style="{background:'#afafaf',color:'#606266'}"
			ref="multipleTable"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="50" align="center"></el-table-column>
			<el-table-column prop="userAccountName" align="center" label="用户名"></el-table-column>
			<el-table-column prop="userNickName" align="center" label="昵称"></el-table-column>
			<el-table-column prop="userHeadImageUrl" align="center" label="头像" width="260">
				<template slot-scope="scope">
					<img v-image-preview :src="scope.row.userHeadImageUrl" width="50" height="50" />
				</template>
			</el-table-column>
      		<!-- <el-table-column prop="address" align="center" label="权限"></el-table-column> -->
            <el-table-column prop="userLastLoginTime" align="center" label="最后登录" width="260">
                <template slot-scope="scope">
                    <span>{{scope.row.userLastLoginTime === null ?"还未登录过":$timeUtil.getFormatTime(scope.row.userLastLoginTime)}}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否启用" align="center" width="260">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.userState"
                        :active-value="1"
                        :inactive-value="2"
                        @change="setStatus(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="160" align="center">
                <template slot-scope="scope">
                    <!-- <el-button type="text" @click="checkRoles(scope.row.userId)" size="small">设置角色</el-button>
                    <router-link  type="primary" round icon="el-icon-edit" :to="{name: 'USER_ADD', query: {id: scope.row.userId}}">
                        <el-button type="text" size="small" >编辑</el-button>
                    </router-link> -->
                    <el-button @click="openAdd(scope.row)" type="text" size="small">编辑</el-button>
                    <el-button @click="delAll(scope.row.userId)" type="text" size="small"><span style="color: red">删除</span></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- <div class="footer flex-between">
            <div>
                <el-checkbox
                    v-model="checkAll"
                    @change="handleCheckAllChange"
                    >全选
                </el-checkbox>
                <el-button type="primary" v-if="!checkItem" size="mini" @click="delAll">删除</el-button>
            </div>
            <el-pagination
                @current-change="handleCurrentChange"
                :current-page="data.page"
                :page-size="10"
                background
                layout="total, prev, pager, next, jumper"
                :total="count">
            </el-pagination>
        </div> -->

    	<!--  弹出层设置角色  -->
		<el-dialog title="请选择角色" :visible.sync="checkRolesShow" width="30%" destroy-on-close>
			<el-checkbox-group v-model="checkRolesList">
				<div v-for="(item , index) in rolesList" :key="index" >
					<div class="content">
						<el-checkbox :label="item.roleId" :key="item.roleId">{{item.roleName}}</el-checkbox>
					</div>
				</div>
			</el-checkbox-group>
			<div style="margin-top: 20px">
				<el-button type="primary" @click="checkAllRoles" size="mini">全选</el-button>
				<el-button @click="cancelCheckAllRoles" size="mini">取消全选</el-button>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="checkRolesShow = false">取 消</el-button>
				<el-button type="primary" @click="changeRole">确 定</el-button>
			</span>
		</el-dialog>

		<el-dialog
            title="新增账号"
            :visible.sync="openAddPage"
            destroy-on-close
            :close-on-click-modal="false"
            @close="getMsgFormSon">
			<userAdd
                :infos="infos"
                ref="usersRef"
                :rolesList="rolesList"
                @func="getMsgFormSon">
            </userAdd>
		</el-dialog>
  	</el-main>
</template>

<script>
    import {
        userList,
        userState,
        roleList,
        userDelete,
        userInfo,
    } from "@/api/table";
    import userAdd from "./userAdd";
    export default {
        name: "USERS_LIST",
        components: {userAdd},
        data() {
            return {
                data:{
                    page: 1
                },
                formData:{},
                dataList: [],
                rolesList:[],
                checkRolesShow: false,
                checkRolesList:[],//绑定角色选择列表
                //当前用户角色列表，用于渲染
                curUserRolesList:[],
                count: 10,
                multipleSelection: [],
                checkAll: false,
                /*弹出新增页面*/
                openAddPage:false,
                checkRoles:[],
                infos: {},
                showLoading: true
            }
        },
        created() {
            this.init();
        },
        methods: {
            init(){
                //获取用户信息，加载表格数据
                let data = JSON.parse(JSON.stringify(this.data));
                data.page --;
                userList(data).then(result => {
                    if (result.code == 200) {
                        const { data } = result.data;
                        this.dataList = data;
                        this.count = data.length;
                    }
                }).finally(_ => {
                    this.showLoading = false
                });
                //获取角色列表，用于设置角色
                roleList().then(res => {
                    if(res.data.isSuccessful !== "Y") {
                        this.$message.error(res.data.message);
                        return
                    }
                    this.rolesList = res.data.data;
                }).catch(err => {});
            },
            //修改状态
            setStatus(userInfo) {
                userState({ userId: userInfo.userId, state: parseInt(userInfo.userState) })
                    .then(res => {
                        if (res.data.isSuccessful === "Y") {
                            this.$message({
                                message: "操作成功",
                                type: "success"
                            });
                        } else {
                            this.$message.error(res.data.message);
                        }
                    })
                    .catch(err => {
                        this.$message.error(err);
                    });
            },
            //设置角色
            changeRole() {
                //组装选择的角色数据
                let roles  = "";
                for (let i=0 ;i< this.checkRolesList.length ;i++){
                    if(i===0){
                        roles += this.checkRolesList[i]
                    }else {
                        roles += ','+this.checkRolesList[i]
                    }
                }
                console.log(roles);
                //todo  修改角色
                //todo 修改完之后将弹出层关闭 或者重加载列表
                this.checkRolesShow = false;
            },
            checkAllRoles() {
              //将checkRolesList赋值\
                let list = [];
                this.rolesList.forEach(e => {
                    list.push(e.roleId)
                });
                this.checkRolesList = list;
            },
            cancelCheckAllRoles() {
                this.checkRolesList = [];
            },
            // handleClose(done) {
            //   this.$confirm('确认关闭？')
            //       .then( e => {
            //           done();
            //       })
            //       .catch(e => {});
            // }
            //监听选择的内容
            handleSelectionChange(val) {
                this.multipleSelection = val;
                this.checkAll = this.dataList.length === val.length
            },
            //加载第几页
            handleCurrentChange(val) {
                this.data.page = val;
                //修改页数，重新加载
                this.init();
            },
            //右下按钮全选，切换保证和表格的全选一致
            handleCheckAllChange(val) {
                if (this.checkAll) {
                    this.$refs.multipleTable.toggleAllSelection();
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            //批量删除
            delAll(rowKey) {
                //是字符串类型则就是 rowKey
                if(typeof(rowKey) =='string'){
                    this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }).then( () => {
                        userDelete(rowKey).then(res => {
                            console.log(res);
                            if (res.code == 200) {
                                this.$message({
                                    message: "删除成功",
                                    type: "success"
                                });
                                setTimeout(() => {
                                    this.init();
                                }, 2000);
                                //跳转到列表
                            } else {
                                this.$message.error(res.description);
                            }
                        }).catch(err => {console.log("错误了")});
                    }).catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
                }else {
                    //不是字符串类型是对象类型
                    console.log(this.multipleSelection);

                }
                //todo 组装keys，调用删除接口
            },
            /*打开资源编辑弹出层*/
            openAdd(infos) {
                if (infos) {
                    this.infos = infos;
                    this.$nextTick(() => {
                        this.$refs.usersRef.updateData()
                    })
                }
                this.openAddPage = true;
            },
            getMsgFormSon(data) {
                this.infos = {};
                this.openAddPage = false;
                data && data.refresh && this.init();
            },
            checkRole() {
                this.formData.roleIds = this.checkRoles;
            }
        },
    }
</script>

<style lang="scss" scoped>
  .content {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding: 6px;
    .el-checkbox {
      width: 160px;
      padding: 6px 0;
    }
  }

  .formBox {
    margin-top: 15px;
  }
  .formBox .title {
    margin: 15px 0;
    font-weight: bold;
    color: #333;
  }
  .formItem {
    width: 360px;
  }
  .describe {
    color: #999;
    margin-left: 10px;
  }

</style>
